package com.bit.blog.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtils {
    private static final String secretString = "ir3q9jfjdmsmdgueiasbffqi0def09qefjzk=djdq9ekfLskd0daif";
    private static final SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;//token过期时间7天

    /**
     * 生成token
     * @param claims
     * @return
     */
    public static String genTolen(Map<String, Object> claims){
        String compact = Jwts.builder().setClaims(claims)
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+ EXPIRE_TIME))
                .signWith(key)//设置签名
                .compact();//生成token
        log.info("调用生成token，token:{}", compact);
        return compact;

    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try{
            body = build.parseClaimsJws(token).getBody();
        } catch(ExpiredJwtException e){
            log.error("用户token过期");
        } catch(Exception e){
            log.error("token解析失败");
        }
        return body;

    }
}
